﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
using System.Xml;

using Microsoft.Xrm.Sdk;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using System.IO;

namespace Founder.PKURG.CRMCommon
{
    public class CommonOperator
    {
        public static List<string> ListActivity = new List<string> { "rl_borrowlist", "rl_reimburse", "rl_arlistdetail", "workflow_flowinstance", "quoteclose", "appointment", "campaignactivity", "campaignresponse", "bulkoperation", "email", "serviceappointment", "task", "letter", "phonecall", "orderclose", "recurringappointmentmaster", "fax", "incidentresolution", "opportunityclose" };

        public static PropertyInfo[] GetPropertyInfo<T>(T t)
        {

            PropertyInfo[] propertys = t.GetType().GetProperties()
                     .Where(propertyInfo => propertyInfo.PropertyType.Namespace.Equals("System"))
                     .ToArray();
            return propertys;
        }
        public static List<T> GetTlistByTable<T>(DataTable table) where T : new()
        {

            try
            {
                List<T> lis = new List<T>();
                T t = new T();
                PropertyInfo[] propertys = GetPropertyInfo<T>(t);
                Type typet = t.GetType();
                for (int count = 0; count < table.Rows.Count; count++)
                {
                    t = new T();
                    foreach (PropertyInfo property in propertys)
                    {
                        string propertyName = property.Name;
                        if (propertyName == "nec_companyname")
                        {
                            continue;
                        }
                        string readerValue = table.Rows[count][propertyName].ToString();

                        string propertyTypeName = property.PropertyType.Name;

                        if (propertyTypeName != "String")
                        {
                            if (readerValue == "")
                            {
                                property.SetValue(t, null, null);

                            }
                            else
                            {
                                try
                                {
                                    if (propertyTypeName == "Guid")
                                    {
                                        Guid accountID = new Guid(readerValue);
                                        property.SetValue(t, accountID, null);
                                        continue;
                                    }
                                    if (propertyTypeName == "Boolean")
                                    {
                                        bool bools = Convert.ToBoolean(readerValue);
                                        property.SetValue(t, bools, null);
                                        continue;
                                    }
                                    if (propertyTypeName == "DateTime")
                                    {
                                        DateTime dt = DateTime.Parse(readerValue);
                                        property.SetValue(t, dt, null);
                                        continue;
                                    }
                                    if (propertyTypeName == "Int32")
                                    {
                                        int proccessdata = Convert.ToInt32(readerValue);
                                        property.SetValue(t, proccessdata, null);
                                        continue;
                                    }
                                    if (propertyTypeName=="Single")
                                    {
                                        float proccessdata = float.Parse(readerValue);
                                        property.SetValue(t, proccessdata, null);
                                        continue;
                                    }
                                    //object obj = Convert.ChangeType(readerValue, property.PropertyType);
                                    //property.SetValue(t, obj, null);
                                }
                                catch
                                {
                                    property.SetValue(t, null, null);
                                    continue;
                                }
                            }

                        }
                        else
                        {
                            property.SetValue(t, readerValue, null);
                        }
                    }


                    lis.Add(t);
                }

                return lis;
            }
            catch (Exception ex)
            {
                throw new ApplicationException(ex.Message);
            }

        }
        public static bool SendMail(EntityCollection fromParty,EntityCollection toParty,string subject,string body)
        {
            Microsoft.Xrm.Sdk.Entity email = new Microsoft.Xrm.Sdk.Entity("email");
            email["from"] = fromParty;
            email["to"] = toParty;
            email["subject"] = subject;
            email["description"] = body;
            Guid emailId = AdminCrmConnect.OrgService.Create(email);
            try
            {
                SendEmailRequest sendEmailreq = new SendEmailRequest
                {
                    EmailId = emailId,
                    TrackingToken = "",
                    IssueSend = true
                };
                SendEmailResponse sendEmailresp = (SendEmailResponse)AdminCrmConnect.OrgService.Execute(sendEmailreq);
            }
            catch (Exception e)
            {
                throw new ApplicationException(e.Message);
            }
            return true;
        }
        public static void WriteLog(string log)
        {
             System.IO.StreamWriter w2 = System.IO.File.AppendText("c:\\crmlog\\logfile.txt");
                w2.WriteLine("记录时间:{0}", DateTime.Now.ToString());
                w2.WriteLine("信息文本:{0}", log);
                w2.WriteLine("---------------------------------------------------------------------------------------------");
                w2.Flush();
                w2.Close();
        }

        /// <summary>
        /// read xml key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string ReadXML(string key)
        {
            string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.xml");
            if (!File.Exists(path))
            {
                path = @"C:\CrmConfinger\config.xml";
            }

            if (!File.Exists(path))
            {
                throw new FileNotFoundException("没有找到crm配置文件");
            }

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(path);
            XmlNode root = xmlDoc.SelectSingleNode("CRMConnect");
            XmlNode node = root.SelectSingleNode(key);

            if (!string.IsNullOrEmpty(node.InnerText))
                return node.InnerText;
            else
                return string.Empty;
            
        }
        //public static void WriteInterFaceLog(InterFaceLog log)
        //{
        //    Entity entity = new Entity("rl_syninfo");
        //    entity["rl_bid"] = log.BID;
        //    entity["rl_erpid"] = log.ERPID;
        //    entity["rl_issuccess"] = log.IsSuccess;
        //    entity["rl_name"] = log.Name;
        //    entity["rl_note"] = log.Note;
        //    entity["rl_sysuser"] = new EntityReference("systemuser",log.SysUser);
        //    entity["rl_type"] = log.Type;
        //    try
        //    {
        //        Guid SynInfo = AdminCrmConnect.OrgService.Create(entity);
        //        AssignRequest assign = new AssignRequest
        //                    {
        //                        Assignee = new EntityReference("systemuser", log.SysUser),
        //                        Target = new EntityReference("rl_syninfo", SynInfo)
        //                    };
        //        AdminCrmConnect.OrgService.Execute(assign);
        //    }
        //    catch(Exception ex)
        //    {
        //        throw new Exception("当前人员没有对接口日志表读写权限");
        //    }

        //}
        #region 检索管理员的角色的用户
        public  static EntityCollection RetrieveAdmin(IOrganizationService ServiceProxy)
        {
            try
            {
                QueryExpression query = new QueryExpression("systemuser");
                query.ColumnSet.AddColumns("systemuserid");
                query.Criteria = new FilterExpression();
                query.Criteria.AddCondition("domainname", ConditionOperator.Like, "%admin%");

                return ServiceProxy.RetrieveMultiple(query);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
        #endregion

    }
}
